package com.v1.video.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebSettings.PluginState;
import android.webkit.WebView;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.v1.video.R;
import com.v1.video.domain.LoginInfo;
import com.v1.video.domain.ResultInfo;
import com.v1.video.domain.TickEntity;
import com.v1.video.engine.NetEngine;
import com.v1.video.httpmanager.RequestManager.OnResponseListener;
import com.v1.video.util.Logger;
import com.v1.video.view.jsbridge.BridgeHandler;
import com.v1.video.view.jsbridge.BridgeWebView;
import com.v1.video.view.jsbridge.BridgeWebViewClient;
import com.v1.video.view.jsbridge.CallBackFunction;
import com.v1.video.view.jsbridge.DefaultHandler;

public class WebViewActivity2 extends BaseActivity {

	public static final int PAY_FLAG_PETITION = 1;
	public static final int PAY_FLAG_LIVE = 2;
	private FrameLayout videoview;// 全屏时视频加载view
	private BridgeWebView videowebview;
	private Boolean islandport = true;// true表示此时是竖屏，false表示此时横屏。
	private View xCustomView;
	private xWebChromeClient xwebchromeclient;
	private String url = "http://www.v1.cn/active/v1cnLive.shtml";
	private WebChromeClient.CustomViewCallback xCustomViewCallback;
	private ProgressDialog progressBar = null;
	private String flagStr;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);// 去掉应用标题
		/*
		 * getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
		 * WindowManager.LayoutParams.FLAG_FULLSCREEN);
		 */
		setContentView(R.layout.activity_webview2);

		initwidget();
		initListener();
		// videowebview.loadUrl(url);
	}

	private void initListener() {
		findViewById(R.id.lay_result).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (inCustomView()) {
					hideCustomView();
				} else {
					Intent intent = new Intent();
					intent.putExtra("flag", flagStr);
					setResult(RESULT_OK, intent);
					finish();
				}
			}
		});
	}

	private void initwidget() {
		// TODO Auto-generated method stub
		if (getIntent().getExtras().containsKey("title")) {
			((TextView) findViewById(R.id.tv_title)).setText(getIntent()
					.getExtras().getString("title"));
		} else {
			((TextView) findViewById(R.id.tv_title)).setText("详情");
		}

		progressBar = new ProgressDialog(this);
		progressBar.setTitle("页面加载中,请稍后...");
		// progressBar.setMessage("Loading...");
		progressBar.setMessage("加载中...");

		videoview = (FrameLayout) findViewById(R.id.video_view);
		videowebview = (BridgeWebView) findViewById(R.id.video_webview);
		WebSettings ws = videowebview.getSettings();
		/**
		 * setAllowFileAccess 启用或禁止WebView访问文件数据 setBlockNetworkImage 是否显示网络图像
		 * setBuiltInZoomControls 设置是否支持缩放 setCacheMode 设置缓冲的模式
		 * setDefaultFontSize 设置默认的字体大小 setDefaultTextEncodingName 设置在解码时使用的默认编码
		 * setFixedFontFamily 设置固定使用的字体 setJavaSciptEnabled 设置是否支持Javascript
		 * setLayoutAlgorithm 设置布局方式 setLightTouchEnabled 设置用鼠标激活被选项
		 * setSupportZoom 设置是否支持变焦
		 * */
		videowebview.getSettings().setDisplayZoomControls(true);
		videowebview.getSettings().setSupportZoom(true);
		videowebview.getSettings().setCacheMode(
				videowebview.getSettings().LOAD_NO_CACHE);
		videowebview.getSettings().setLayoutAlgorithm(
				WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
		videowebview.setHorizontalScrollBarEnabled(false);
		videowebview.setVerticalScrollBarEnabled(false);
		videowebview.getSettings().setSupportZoom(false);
		videowebview.getSettings().setJavaScriptEnabled(true);
		videowebview.getSettings().setJavaScriptCanOpenWindowsAutomatically(
				true);
		videowebview.getSettings().setBuiltInZoomControls(true);// support zoom
		// videowebview.getSettings().setPluginsEnabled(true);//support flash
		videowebview.getSettings().setPluginState(PluginState.ON);
		videowebview.getSettings().setUseWideViewPort(true);// 这个很关键
		videowebview.getSettings().setLoadWithOverviewMode(true);
		videowebview.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
		videowebview.setDefaultHandler(new DefaultHandler());
		Intent intent = getIntent();
		String adLink = intent.getStringExtra("adLink");
		int flag = intent.getIntExtra("flag", 0);
		switch (flag) {
		case PAY_FLAG_PETITION: // 加载情愿支付
			String wshid = getIntent().getStringExtra("wshid");
			String tick = getIntent().getStringExtra("tick");
			getCheckTick(adLink, wshid, tick);
			break;
		case PAY_FLAG_LIVE: // 加载直播支付
			String data = getIntent().getStringExtra("data");
			if (!TextUtils.isEmpty(adLink)) {
				Logger.i(TAG, "post参数-->" + data);
				videowebview.postUrl(adLink, data.getBytes());
			}
			break;
		default:
			if (!TextUtils.isEmpty(adLink)) {
				videowebview.loadUrl(adLink);
			}
			break;
		}
		// load a web page
		Logger.i(TAG, "adLink==" + adLink);

		xwebchromeclient = new xWebChromeClient();
		videowebview.setWebChromeClient(xwebchromeclient);
		videowebview.setWebViewClient(new xWebViewClientent(videowebview));
		videowebview.registerHandler("CallBackJs", new BridgeHandler() {

			@Override
			public void handler(String data, CallBackFunction function) {
				// TODO Auto-generated method stub
				Logger.i(TAG, data);
				Gson gson = new Gson();
				ResultInfo Info = gson.fromJson(data, ResultInfo.class);
				flagStr = Info.getCode();
			}
		});
	}

	/**
	 * 加载情愿支付
	 * 
	 * @param url
	 * @param wshid
	 * @param tick
	 */
	private void loadPetitionPay(String url, String wshid, String tick) {
		if (!TextUtils.isEmpty(url)) {
			String postData = "wshid=" + wshid + "&tick=" + tick;
			Logger.i(TAG, "post参数-->" + postData);
			videowebview.postUrl(url, postData.getBytes());
		}
	}

	/**
	 * 加载情愿支付
	 * 
	 * @param url
	 * @param wshid
	 * @param tick
	 */
	private void getCheckTick(final String url, final String wshid,final String tick) {
		if (TextUtils.isEmpty(tick)) {
			new NetEngine().getTick(this, LoginInfo.getInstance().getUserId(),
					new OnResponseListener() {

						@Override
						public void onSuccess(Object object, int code,
								String message, String keyId) {
							// TODO Auto-generated method stub
							if (object != null) {
								TickEntity entity = (TickEntity) object;
								if (entity != null
										&& entity.getBody() != null
										&& entity.getBody().getData() != null
										&& !TextUtils.isEmpty(entity.getBody()
												.getData().getTick())) {
									String tick = entity.getBody().getData()
											.getTick();
									loadPetitionPay(url, wshid, tick);
									saveTick(tick);
								}
							}
						}

						@Override
						public void onFailure(int code, String message) {
							// TODO Auto-generated method stub
							Logger.i(TAG, message);
						}
					});
		} else {
			new NetEngine().getCheckTick(this, LoginInfo.getInstance()
					.getUserId(), tick, new OnResponseListener() {

				@Override
				public void onSuccess(Object object, int code, String message,
						String keyId) {
					// TODO Auto-generated method stub
					if (object != null) {
						TickEntity entity = (TickEntity) object;
						if (entity != null
								&& entity.getBody() != null
								&& entity.getBody().getResult()!=0) {
							String newTick=entity.getBody().getTick();
							if (!TextUtils.isEmpty(newTick)) {
								loadPetitionPay(url, wshid, newTick);
								saveTick(newTick);
							}
							
						} else {
							loadPetitionPay(url, wshid, tick);
						}
					}
				}

				@Override
				public void onFailure(int code, String message) {
					// TODO Auto-generated method stub
					Logger.i(TAG, message);
				}

			});
			
		}
	}
	
	/**
	 * 保存Tick
	 * @param tick
	 */
	private void saveTick(String tick) {
		if (!TextUtils.isEmpty(tick)) {
			LoginInfo.getInstance().setTick(tick);
			LoginInfo.getInstance().saveInstance(this);
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (inCustomView()) {
				hideCustomView();
				return true;
			} else {

				videowebview.loadUrl("about:blank");
				Intent intent = new Intent();
				intent.putExtra("flag", flagStr);
				setResult(RESULT_OK, intent);
				WebViewActivity2.this.finish();
				Log.i("testwebview", "===>>>2");
			}
		}
		return false;
	}

	/**
	 * 判断是否是全屏
	 * 
	 * @return
	 */
	public boolean inCustomView() {
		return (xCustomView != null);
	}

	/**
	 * 全屏时按返加键执行退出全屏方法
	 */
	public void hideCustomView() {
		xwebchromeclient.onHideCustomView();
	}

	/**
	 * 处理Javascript的对话框、网站图标、网站标题以及网页加载进度等
	 * 
	 * @author
	 */
	public class xWebChromeClient extends WebChromeClient {
		private Bitmap xdefaltvideo;
		private View xprogressvideo;

		@Override
		// 播放网络视频时全屏会被调用的方法
		public void onShowCustomView(View view,
				WebChromeClient.CustomViewCallback callback) {
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
			videowebview.setVisibility(View.GONE);
			// 如果一个视图已经存在，那么立刻终止并新建一个
			if (xCustomView != null) {
				callback.onCustomViewHidden();
				return;
			}

			videoview.addView(view);
			xCustomView = view;
			xCustomViewCallback = callback;
			videoview.setVisibility(View.VISIBLE);
		}

		@Override
		// 视频播放退出全屏会被调用的
		public void onHideCustomView() {

			if (xCustomView == null)// 不是全屏播放状态
				return;

			// Hide the custom view.
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
			xCustomView.setVisibility(View.GONE);

			// Remove the custom view from its container.
			videoview.removeView(xCustomView);
			xCustomView = null;
			videoview.setVisibility(View.GONE);
			xCustomViewCallback.onCustomViewHidden();

			videowebview.setVisibility(View.VISIBLE);

			// Log.i(LOGTAG, "set it to webVew");
		}

		// 视频加载添加默认图标
		@Override
		public Bitmap getDefaultVideoPoster() {
			// Log.i(LOGTAG, "here in on getDefaultVideoPoster");
			if (xdefaltvideo == null) {
				xdefaltvideo = BitmapFactory.decodeResource(getResources(),
						R.drawable.ic_launcher);
			}
			return xdefaltvideo;
		}

		// 视频加载时进程loading
		@Override
		public View getVideoLoadingProgressView() {
			// Log.i(LOGTAG, "here in on getVideoLoadingPregressView");

			if (xprogressvideo == null) {
				LayoutInflater inflater = LayoutInflater
						.from(WebViewActivity2.this);
				xprogressvideo = inflater.inflate(
						R.layout.video_loading_progress, null);
			}
			return xprogressvideo;
		}

		// 网页标题
		@Override
		public void onReceivedTitle(WebView view, String title) {
			(WebViewActivity2.this).setTitle(title);
		}

		@Override
		public void onProgressChanged(WebView view, int newProgress) {
			progressBar.setProgress(newProgress);
			// progressBar.setMessage("Loading..."+newProgress+"%");
			progressBar.setMessage("加载中..." + newProgress + "%");
			if (newProgress >= 100)
				progressBar.dismiss();
			super.onProgressChanged(view, newProgress);
		}

	}

	/**
	 * 处理各种通知、请求等事件
	 * 
	 * @author
	 */
	public class xWebViewClientent extends BridgeWebViewClient {

		public xWebViewClientent(BridgeWebView webView) {
			super(webView);
			// TODO Auto-generated constructor stub
		}

		// @Override
		// public boolean shouldOverrideUrlLoading(WebView view, String url) {
		// Log.i("webviewtest", "shouldOverrideUrlLoading: " + url);
		// return false;
		// }

		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			progressBar.show();
			super.onPageStarted(view, url, favicon);
		}

		@Override
		public void onPageFinished(WebView view, String url) {
			if (progressBar.isShowing()) {
				progressBar.dismiss();
			}
			super.onPageFinished(view, url);
		}

	}

	/**
	 * 当横竖屏切换时会调用该方法
	 * 
	 * @author
	 */
	/*
	 * @Override public void onConfigurationChanged(Configuration newConfig) {
	 * Log.i("testwebview", "=====<<<  onConfigurationChanged  >>>=====");
	 * super.onConfigurationChanged(newConfig);
	 * 
	 * if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
	 * Log.i("webview", "   现在是横屏1"); islandport = false; } else if
	 * (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
	 * Log.i("webview", "   现在是竖屏1"); islandport = true; } }
	 */

	@Override
	protected void onPause() {
		videowebview.onPause();
		super.onPause();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		videowebview.onResume();
	}
}
